﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace deFramework.BusinessRules
{
    public class XmlAsInfoPathFormBR: Base.BaseBusinessRule
    {
        #region "Constructor, private Variables"
		
        /// <summary>
        /// 
        /// </summary>
        /// <param name="aContext"></param>
        public XmlAsInfoPathFormBR(ref Common.PresentationContext aContext) : base(ref aContext) { }  
 
 
		#endregion



        #region "Biz Rule code"

        /// <summary>
        /// Assumes that all 16 required param values have been set.
        /// 1. Load template XML 
        /// 2. Fill-in template XML with values. 
        /// 3. Fill-in system values. 
        /// 4. Save to file system. 
        /// 5. Upload to server. 
        /// 6. Behind-the-scenes .... document library event handler starts 
        /// workflow to create Intake Task + Request Summary
        /// </summary>
        /// <param name="formTemplateUrl"></param>
        /// <param name="siteUrl"></param>
        /// <param name="formsLibraryName"></param>
        /// <param name="serverTempDirectory"></param>
        /// <returns></returns>
        private bool Old_SubmitTipLeadForm(string formTemplateUrl, string siteCollectUrl,
            string formsLibraryName, string serverTempDirectory)
        {
            bool _result = false;
            try
            {
                string nowString = System.DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss");
                string fileName = "TL_" + nowString.Replace(":", "_") + ".xml";
                string filePath = serverTempDirectory + "\\" + fileName;
                string libraryUrl = siteCollectUrl + "/" + formsLibraryName;

                string xml = this.LoadTemplateXml(formTemplateUrl);
                xml = this.ReplaceParamsInXml(xml, nowString);
                this.XmlContents = xml;

                this.SaveStringAsTextFile(xml, filePath);
                this.UploadLocalFileToSiteCollectionLibrary(
                    siteCollectUrl, libraryUrl, formsLibraryName, filePath, fileName);
            }
            catch (Exception ex)
            {

                this.CurrentException = ex;
            }
            return _result;
        }



        private string Details_SubmitTipLeadForm()
        {
            string _result = "N";
            string placeCode = "d1"; 
            try
            {
                string nowString = System.DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss");
                string fileName = "TL_" + nowString.Replace(":", "_") + ".xml";
                string filePath = this.Param_ServerTempDirectory + "\\" + fileName;
                string libraryUrl = this.Param_SiteCollectUrl + "/" + this.Param_FormsLibraryName;
                placeCode = "d2: now=" + nowString + "; file=" + filePath + "; library=" + libraryUrl; 

                string xml = this.LoadTemplateXml(this.Param_FormTemplateUrl);
                placeCode = "d3"; 
                xml = this.ReplaceParamsInXml(xml, nowString);
                placeCode = "d4";
                this.XmlContents = xml;

                this.SaveStringAsTextFile(xml, filePath);
                placeCode = "d5-" + this.Param_SiteCollectUrl + "; library=" + libraryUrl;
                this.UploadLocalFileToSiteCollectionLibrary(
                    this.Param_SiteCollectUrl, libraryUrl, this.Param_FormsLibraryName, filePath, fileName);
                placeCode = "d6"; 

                _result = "Y"; 
            }
            catch (Exception ex)
            {

                Exception throwUp = new Exception("placeCode=" + placeCode + "; " + ex.Message, ex);
                this.CurrentException = throwUp;
            }
            return _result;
        }

        private string Param_FormTemplateUrl = String.Empty;
        private string Param_SiteCollectUrl = String.Empty;
        private string Param_FormsLibraryName = String.Empty;
        private string Param_ServerTempDirectory = String.Empty;

        private void SetParams_SubmitTipLeadForm(string formTemplateUrl, string siteCollectUrl,
            string formsLibraryName, string serverTempDirectory)
        {
            this.Param_FormTemplateUrl = formTemplateUrl;
            this.Param_SiteCollectUrl = siteCollectUrl;
            this.Param_FormsLibraryName = formsLibraryName;
            this.Param_ServerTempDirectory = serverTempDirectory;
        }


        public bool SubmitTipLeadForm(string formTemplateUrl, string siteCollectUrl,
            string formsLibraryName, string serverTempDirectory)
        {
            string _result = String.Empty;
            string placeCode = "1";
            Microsoft.SharePoint.SPWeb webDefault = this.MyContext.MySpWeb;
            try
            {
                this.MyContext.MySpWeb = this.GetSpWeb(siteCollectUrl);
                this.SetParams_SubmitTipLeadForm(formTemplateUrl, siteCollectUrl, formsLibraryName, serverTempDirectory); 
                placeCode = "2";
                _result = this.ElevatedSharePointProcessing(new MethodNoParameters(this.Details_SubmitTipLeadForm));
               placeCode = "3"; 
            }
            catch (Exception ex)
            {
                Exception throwUp = new Exception("placeCode=" + placeCode + "; " + ex.Message, ex);
                this.CurrentException = throwUp;
            }
            finally
            {
                Microsoft.SharePoint.SPWeb tempWeb = this.MyContext.MySpWeb;
                tempWeb.Dispose();
                this.MyContext.MySpWeb = webDefault;
            }
            if (_result.Trim().Length > 0)
                return (_result.Trim().Substring(0,1).ToUpper()=="Y"); 
            else 
                return false; 
        }


        #region "Subs - LoadTemplateXml, ReplaceParamsInXml, StringSearchReplace, xxx, xxx"


        private string LoadTemplateXml(string infoPathFormUrl)
        {
            string _result = String.Empty;
            Microsoft.SharePoint.SPListItem itemFile = null;
            System.Xml.XmlDocument xmlDoc =
                this.LoadSpFileItemAsInfoPathXmlDoc(infoPathFormUrl, out itemFile);
            _result = xmlDoc.OuterXml;
            return _result;
        }

        private string ReplaceParamsInXml(string xmlTemplate, string nowString)
        {
            string xml = xmlTemplate;
            //xml = this.TipLeadDataReplace(xml, "UserId", this.UserId);
            xml = this.TipLeadDataReplace(xml, "AgencyName", this.AgencyName);

            xml = this.TipLeadDataReplace(xml, "LocationStreet", this.LocationStreet);
            xml = this.TipLeadDataReplace(xml, "LocationCity", this.LocationCity);
            //xml = this.TipLeadDataReplace(xml, "LocationState", this.LocationState);
            xml = this.TipLeadDataReplace(xml, "LocationZip", this.LocationZip);

            xml = this.TipLeadDataReplace(xml, "ShortDescription", this.ShortDescription);
            xml = this.TipLeadDataReplace(xml, "LongNarrative", this.LongNarrative);
            xml = this.TipLeadDataReplace(xml, "AgencyOri", this.AgencyOri);
            xml = this.TipLeadDataReplace(xml, "SubmitterFax", this.SubmitterFax);

            xml = this.TipLeadDataReplace(xml, "SubmitterPhone", this.SubmitterPhone);
            xml = this.TipLeadDataReplace(xml, "SubmitterEmail", this.SubmitterEmail);
            xml = this.TipLeadDataReplace(xml, "CaseNumber", this.CaseNumber);

            string submitterFirst = this.SubmitterName;
            string submitterLast = this.SubmitterName;
            this.SplitNameIntoFirstLast(this.SubmitterName, out submitterFirst, out submitterLast);
            xml = this.TipLeadDataReplace(xml, "SubmitterName:0", submitterFirst);
            xml = this.TipLeadDataReplace(xml, "SubmitterName:1", submitterLast);

            string kUtah = "<fusionx:StateName>UT</fusionx:StateName>";
            string kOutState = "<fusionx:StateName>{0}</fusionx:StateName>";
            if (!(this.LocationState.ToUpper().Trim().StartsWith("UT")) &&
                this.LocationState.ToUpper().Trim().Length > 1)
                xml = xml.Replace(kUtah, String.Format(kOutState,
                    this.LocationState.ToUpper().Trim().Substring(0, 2)));

            xml = this.StringSearchReplace(xml, "2010-08-01T01:01:01", nowString);
            if (this.UserId.Trim().Length > 0)
                xml = this.StringSearchReplace(xml, "Form created by WebServiceEndUser",
                    "Form created by " + this.SystemName + "." + this.UserId);
            return xml;
        }

        private string StringSearchReplace(string origString, string searchString, string replaceString)
        {
            string _result = origString;
            int countEndlessLoop = 0;
            while (countEndlessLoop < 100 && _result.Contains(searchString))
            {
                _result = _result.Replace(searchString, replaceString);
                countEndlessLoop++;
            }
            return _result;

        }


        private void SaveStringAsTextFile(string contents, string localFilePath)
        {
            System.IO.StreamWriter outfile = new System.IO.StreamWriter(localFilePath);
            outfile.Write(contents);
            outfile.Close();
            outfile.Dispose();
        }

        private void UploadLocalFileToSiteCollectionLibrary(string siteCollectUrl, string formsLibraryUrl, string formsLibraryName, string localFilePath, string uploadFileName)
        {
            Microsoft.SharePoint.SPSite sp = new Microsoft.SharePoint.SPSite(siteCollectUrl);
            Microsoft.SharePoint.SPWeb site = sp.OpenWeb();
            try
            {
                Microsoft.SharePoint.SPFolder folder = site.GetFolder(formsLibraryName);
                Microsoft.SharePoint.SPFileCollection files = folder.Files;
                System.IO.FileStream fStream = System.IO.File.OpenRead(localFilePath); //path of the file to upload      

                byte[] contents = new byte[fStream.Length];
                fStream.Read(contents, 0, (int)fStream.Length);
                fStream.Close();

                System.Collections.Hashtable metaDataTable = new System.Collections.Hashtable();
                metaDataTable.Add("Comments", "Siac Fusion Core Web Service Upload");
                Microsoft.SharePoint.SPFile currentFile = files.Add(
                formsLibraryUrl + "/" + uploadFileName, contents, metaDataTable, true);
            }
            finally
            {
                site.Dispose();
            }

        }


        #endregion




        #region "Misc Biz Rule supporting routines - TipLeadDataReplace, SplitNameIntoFirstLast, AuthenticateWebServiceSystem, XmlContents"

        private string TipLeadDataReplace(string theString, string fieldName, string value)
        {
            string kPrefix = "WebService:TipLead:";
            theString = this.StringSearchReplace(theString, kPrefix + fieldName, value);
            return theString;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="fullName"></param>
        /// <param name="firstName"></param>
        /// <param name="lastName"></param>
        /// <returns>True=Straightforward; False=Complicated and made guess</returns>
        protected bool SplitNameIntoFirstLast(string fullName, out string firstName, out string lastName)
        {
            bool _result = true;
            string rawName = fullName.Trim();
            string rawLast = rawName;
            string rawFirst = String.Empty;
            int posSpace1 = rawName.IndexOf(" ");
            if (posSpace1 > 0)
            {
                rawFirst = rawName.Substring(0, posSpace1);
                rawLast = rawName.Substring(1 + posSpace1).Trim();
                _result = !(rawLast.Contains(" "));
            }
            else
                _result = false;
            firstName = rawFirst;
            lastName = rawLast;
            return _result;
        }


        public bool AuthenticateWebServiceSystem(string systemName, string password)
        {
            bool _result = false;
            try
            {
                string key = systemName + "password";
                string value = System.Configuration.ConfigurationManager.AppSettings[key].ToString();
                _result = (value == password);
            }
            catch (Exception ex)
            {
                this.CurrentException = ex;
            }
            return _result;
        }


        public string XmlContents = String.Empty;

        #endregion


        #region "Public Service-Security Variables"

        #region "SystemName, SystemPassword, UserId, AgencyName"

        private string _systemName = "";
        private string _systemPassword = "";
        private string _userId = "";
        private string _agencyName = "";


        /// <remarks/>
        public string SystemName
        {
            get
            {
                return this._systemName;
            }
            set
            {
                this._systemName = value;
            }
        }


        /// <remarks/>
        public string SystemPassword
        {
            get
            {
                return this._systemPassword;
            }
            set
            {
                this._systemPassword = value;
            }
        }

        /// <remarks/>
        public string UserId
        {
            get
            {
                return this._userId;
            }
            set
            {
                this._userId = value;
            }
        }


        /// <remarks/>
        public string AgencyName
        {
            get
            {
                return this._agencyName;
            }
            set
            {
                this._agencyName = value;
            }
        }

        #endregion


        #endregion

        #region "Public Service-Specific Variables"

        #region "Other - LocationStreet, LocationCity, LocationState, LocationZip"

        private string _locationStreet = "";
        private string _locationCity = "";
        private string _locationState = "";
        private string _locationZip = "";




        /// <remarks/>
        public string LocationStreet
        {
            get
            {
                return this._locationStreet;
            }
            set
            {
                this._locationStreet = value;
            }
        }


        /// <remarks/>
        public string LocationCity
        {
            get
            {
                return this._locationCity;
            }
            set
            {
                this._locationCity = value;
            }
        }

        /// <remarks/>
        public string LocationState
        {
            get
            {
                return this._locationState;
            }
            set
            {
                this._locationState = value;
            }
        }



        /// <remarks/>
        public string LocationZip
        {
            get
            {
                return this._locationZip;
            }
            set
            {
                this._locationZip = value;
            }
        }

        #endregion

        #region "Other - ShortDescription, LongNarrative, AgencyOri, SubmitterFax"





        private string _shortDescription = "";
        private string _longNarrative = "";
        private string _agencyOri = "";
        private string _submitterFax = "";


        /// <remarks/>
        public string ShortDescription
        {
            get
            {
                return this._shortDescription;
            }
            set
            {
                this._shortDescription = value;
            }
        }

        //        string shortDescription, string longNarrative,
        //string agencyOri, string submitterFax


        /// <remarks/>
        public string LongNarrative
        {
            get
            {
                return this._longNarrative;
            }
            set
            {
                this._longNarrative = value;
            }
        }


        /// <remarks/>
        public string AgencyOri
        {
            get
            {
                return this._agencyOri;
            }
            set
            {
                this._agencyOri = value;
            }
        }



        /// <remarks/>
        public string SubmitterFax
        {
            get
            {
                return this._submitterFax;
            }
            set
            {
                this._submitterFax = value;
            }
        }

        #endregion

        #region "Other - SubmitterName, SubmitterPhone, SubmitterEmail, CaseNumber"

        private string _submitterName = "";
        private string _submitterPhone = "";
        private string _submitterEmail = "";
        private string _caseNumber = "";




        /// <remarks/>
        public string SubmitterName
        {
            get
            {
                return this._submitterName;
            }
            set
            {
                this._submitterName = value;
            }
        }


        /// <remarks/>
        public string SubmitterPhone
        {
            get
            {
                return this._submitterPhone;
            }
            set
            {
                this._submitterPhone = value;
            }
        }

        /// <remarks/>
        public string SubmitterEmail
        {
            get
            {
                return this._submitterEmail;
            }
            set
            {
                this._submitterEmail = value;
            }
        }



        /// <remarks/>
        public string CaseNumber
        {
            get
            {
                return this._caseNumber;
            }
            set
            {
                this._caseNumber = value;
            }
        }

        #endregion


        #endregion



        #endregion




    }
}
